package com.pignest.hotel.dao.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.pignest.framework.dao.BaseHibernateDao;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Role;
import com.pignest.hotel.beans.User;
import com.pignest.hotel.dao.UserDao;

@SuppressWarnings("unchecked")
public class UserHibernateDao extends BaseHibernateDao implements UserDao {

//	public boolean exists(String workNo) {
//		List l = getHibernateTemplate().find("from User where workNumber=? ", new Object[] {workNo});
//		return l != null && !l.isEmpty();
//	}

	@Override
	public User getUserByWorkNo(String workNo) {
		List<User> l = getHibernateTemplate().find("from User where workNumber=? ", new Object[] {workNo});
		return l != null && !l.isEmpty() ? l.get(0) : null;
	}

	@Override
	public User getUserByCardNumber(String cardNumber) {
		List<User> l = getHibernateTemplate().find("from User where cardNumber=? ", new Object[] {cardNumber});
		return l != null && !l.isEmpty() ? l.get(0) : null;
	}
	@Override
	public String getCardNumberBySnr(String snr){
		List<Card> l= getHibernateTemplate().find(" from Card where serialNumber=?",new Object[]{snr});
		return l!=null&&!l.isEmpty()? l.get(0).getCardNumber():null;
	}
	public List<User> findUsers(final String keyword, final boolean enable, final Role role) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				StringBuilder sb = new StringBuilder("select user from User user");
				if (role != null) {
					sb.append(",UserRole ur where ur.user=user and ur.role=:role");
				} else {
					sb.append(" where 1=1");
				}
				boolean k = StringUtils.isNotEmpty(keyword);
				if (k)
					sb.append(" and (user.name like :keyword or user.remark like :keyword or user.workNumber like :keyword or user.cardNumber like :keyword)");
				if (enable)
					sb.append(" and user.enable=true");
				Query q = session.createQuery(sb.toString());
				if (role != null)
					q.setParameter("role", role);
				if (k)
					q.setString("keyword", "%" + keyword + "%");
				return q.list();
			}
		});
	}
}
